﻿using System;
using System.Collections.Generic;
using Pay.Core;
using Pay.Service.Cache;

namespace Pay.Service {
    /// <summary>
    /// 缓存
    /// </summary>
    public static class CacheHelper {
        private static object _cacheLocker = new object();//缓存锁对象
        private static ICache _cache = null;//缓存接口

        static CacheHelper() {
            Load();
        }

        /// <summary>
        /// 加载缓存
        /// </summary>
        private static void Load() {
            try {
                _cache = new MemcachedHelper();
            } catch (Exception ex) {
                IocHelper.Get<ILogHelper>("data_change").Info("new MemcachedHelper: " + ex.Message);
            }
        }

        /// <summary>
        /// 获得指定键的缓存值
        /// </summary>
        /// <param name="key">缓存键</param>
        /// <returns>缓存值</returns>
        public static T Get<T>(string key) {
            return _cache.Get<T>(key);
        }

        /// <summary>
        /// 将指定键的对象添加到缓存中
        /// </summary>
        /// <returns>The or create.</returns>
        /// <param name="cacheKey">Cache key.</param>
        /// <param name="create">Create.</param>
        /// <param name="seconds">Seconds.</param>
        /// <typeparam name="T">The 1st type parameter.</typeparam>
        public static T GetOrCreate<T>(string cacheKey, Func<T> create, int seconds = int.MaxValue) {
            return _cache.GetOrCreate<T>(cacheKey, create, seconds);
        }

        /// <summary>
        /// 将指定键的对象添加到缓存中
        /// </summary>
        /// <returns>The set.</returns>
        /// <param name="key">Key.</param>
        /// <param name="value">Value.</param>
        /// <param name="seconds">Seconds.</param>
        public static bool Set(string key, object value, int seconds = 0) {
            if (string.IsNullOrWhiteSpace(key) || value == null)
                return false;
            return _cache.Set(key, value, seconds);
        }

        /// <summary>
        /// 从缓存中移除指定键的缓存值
        /// </summary>
        /// <param name="key">缓存键</param>
        public static bool Remove(string key) {
            if (string.IsNullOrWhiteSpace(key))
                return false;
            return _cache.Remove(key);
        }

        public static void Remove(IEnumerable<string> tags) {
            _cache.Remove(tags);
        }

        public static void RemoveAll() {
            _cache.RemoveAll();
        }
    }
}